import os
import subprocess

from PyQt5 import QtWidgets
from PyQt5.QtCore import pyqtSlot, QStringListModel, QUrl
from PyQt5.QtGui import QDesktopServices
from PyQt5.QtWidgets import QMainWindow

from UserInterface.MainUI import Ui_MainWinForm
from Util.ExcelUtil import ExcelUtil
from Util.NewTab import WebEngineView


class VideoManagerApp(QMainWindow, Ui_MainWinForm):
    def __init__(self, serverAddr="localhost", parent=None):
        super(VideoManagerApp, self).__init__(parent)
        self.setupUi(self)
        self.retranslateUi(self)
        self.cameraList = []
        self.listModel = QStringListModel()
        self.listView.clicked.connect(self.onlistViewClicked)

        self.serverAddr = serverAddr
        self.newTabWindows = []
        self.newTabWindows.append(WebEngineView("https://www.baidu.com", "Title"))
        self.newTabNums = 1
        return

    @pyqtSlot()
    def on_importlist_clicked(self):
        print("import")
        fileOpenWindow = QtWidgets.QMainWindow()
        xlPathTemp = QtWidgets.QFileDialog.getOpenFileName(fileOpenWindow, "选择文件", os.getcwd(),
                                                           "Excel文档(*.xls)")
        print(xlPathTemp[0] + " " + xlPathTemp[1])  # debug
        if not xlPathTemp[0] == "":
            self.cameraList = ExcelUtil.getListByXlFile(xlPathTemp[0])
            print("Successfully get camera list.")  # debug
            cameraListOnUI = []
            for eachCamera in self.cameraList[1:]:
                if eachCamera[0] == "":
                    eachCamera[0] = "未命名"
                cameraListOnUI.append(eachCamera[0] + "\n" + eachCamera[1] + "\n")
            print("Successfully generate list on UI.")  # debug
            self.listModel.setStringList(cameraListOnUI)
            self.listView.setModel(self.listModel)
        return

    def onlistViewClicked(self, item):
        print("Selected: ", item.row())  # debug
        _thisNumber = str(self.cameraList[item.row() + 1][1])
        _thisUrl = "http://" + self.serverAddr + ":3333/test/multimedia#" + _thisNumber + "-2"
        # _thisUrl = "https://www.bilibili.com/video/BV1vx411E7Mb"
        # self.newTabWindows.append(WebEngineView(_thisUrl, _thisNumber))
        # self.newTabWindows[self.newTabNums].show()
        # self.newTabNums += 1
        QDesktopServices.openUrl(QUrl(_thisUrl))

    @pyqtSlot()
    def on_flowmonitor_clicked(self):
        print("Flow monitor.")
        try:
            _cmd = "python " + os.getcwd() + "\\Util\\FlowMonitor.py"
            print(_cmd)
            subprocess.Popen(_cmd)
        except:
            print("Error.")
